package com.lovo.market.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author MirAi
 * @description Json转换类
 * @date 2020/12/15 22:11
 */
public final class JsonTransferUtil {

    /** 转换工具 */
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将对象转换为json字符串
     *
     * @param pojo 对象
     * @return json字符串
     */
    public static String pojoToJson(Object pojo) {

        try {
            return OBJECT_MAPPER.writeValueAsString(pojo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将json字符串转换为对象
     *
     * @param json json字符串
     * @param pojoClass 对象类模板
     * @return 对象
     */
    public static <Pojo> Pojo jsonToPojo(String json, Class<Pojo> pojoClass) {

        try {
            return OBJECT_MAPPER.readValue(json, pojoClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }
}
